package com.kqb.sgauth.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kqb.sgauth.model.UserAccount;
import com.kqb.sgauth.service.UserAccountService;
import com.kqb.sgauth.mapper.UserAccountMapper;
import com.kqb.sgcommon.base.utils.ThrowUtils;
import com.kqb.sgcommon.satoken.StpKit;
import org.springframework.stereotype.Service;

/**
 * @author D
 * @description 针对表【t_user_account(用户基本信息表)】的数据库操作Service实现
 * @createDate 2025-06-14 13:59:59
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount>
        implements UserAccountService {

    @Override
    public UserAccount getUserAccountByOpenId(String openId) {
        QueryWrapper<UserAccount> qw = new QueryWrapper<UserAccount>().eq("openid", openId);
        return baseMapper.selectOne(qw);
    }

    @Override
    public int updateUserPhone(String phone) {
        SaTokenInfo tokenInfo = StpKit.USER.getTokenInfo();
        String openid = (String) tokenInfo.getLoginId();
        UserAccount userAccount = new UserAccount();
        userAccount.setOpenid(openid);
        userAccount.setPhone(phone);
        return this.updateByOpenId(userAccount);
    }

    @Override
    public int updateUserAvatar(String avatarUrl) {
        SaTokenInfo tokenInfo = StpKit.USER.getTokenInfo();
        String openid = (String) tokenInfo.getLoginId();
        UserAccount userAccount = new UserAccount();
        userAccount.setOpenid(openid);
        userAccount.setAvatar(avatarUrl);
        return this.updateByOpenId(userAccount);
    }

    @Override
    public int updateUserNickName(String nickName) {
        SaTokenInfo tokenInfo = StpKit.USER.getTokenInfo();
        String openid = (String) tokenInfo.getLoginId();
        UserAccount userAccount = new UserAccount();
        userAccount.setOpenid(openid);
        userAccount.setNick(nickName);
        return this.updateByOpenId(userAccount);
    }

    @Override
    public int updateByOpenId(UserAccount userAccount) {
        if (userAccount == null) {
            throw new RuntimeException("参数不能为空");
        }
        UpdateWrapper<UserAccount> uw = new UpdateWrapper<UserAccount>()
                .eq("openid", userAccount.getOpenid())
                .set(userAccount.getAvatar() != null, "avatar", userAccount.getAvatar())
                .set(userAccount.getNick() != null, "nick", userAccount.getNick())
                .set(userAccount.getPhone() != null, "phone", userAccount.getPhone());
        int res = baseMapper.update(userAccount, uw);
        ThrowUtils.throwNotIf(res > 0, new RuntimeException("更新用户信息失败"));
        return res;
    }

}




